'use strict'

process.chdir(__dirname)

const threads = require('../index')

//要通过线程运行的文件以及选项，其参数可以直接参照Node.js官方文档
let worker = threads('thread-child.js', {
    //如果你要给a.js传递参数，要使用此选项。
    //请参考官方文档对选项的描述。
    argv: [],

    restart: 'fail',

    restartDelay: 1000,

    events: {
        message: async (w, msg) => {
            console.log('get message from', w.threadId, msg)
            await new Promise((rv) => { setTimeout(rv, 1000) })
            w.postMessage({msg: 'ok, recived', time: (new Date).toLocaleString()})
        },

        // w就是worker，扩展做了包装处理，
        // 这样方便拿到worker对象。
        exit: (w, code) => {
            console.log(w.threadId, code, 'exit')
        }
    }
})

worker.on('online', () => {
    console.log(worker.threadId, 'running')
})

worker.on('message', (msg) => {
  console.log('get message ===>', msg)
})

worker.postMessage({
    tid: worker.threadId,
    say: 'ok'
})

